<template>
    <div class="brand-total-page">
      <!-- 顶部信息卡片 -->
      <div class="info-card">
        <div class="info-content">
          <div class="info-image">
            <img src="/banner2.jpg" alt="主要电子产品总体销售分析" />
          </div>
          <div class="info-text">
            <h2>📊 主要电子产品总体销售情况分析</h2>
            <p class="desc">
              本图对主要电子产品类别的整体销售情况进行了统计分析，展示了各品牌的销量数量与总销售额的对比。
              <br /><br />
              从整体趋势来看，智能手机、笔记本电脑、电视等核心产品的销量明显领先，体现出其在消费者日常生活中的高需求度；
              同时，家用电器和厨房设备等品类的销售额也表现出稳定增长，说明实用型产品在市场中同样占据重要地位。
              <br /><br />
              通过销量与销售额的双维度分析，品牌方和商家可以直观了解不同产品类别的市场表现，为产品策略、定价和营销方向提供数据支撑。
            </p>
          </div>
        </div>
      </div>
  
      <!-- 柱状图 + 折线图 -->
      <div class="chart-card">
        <div ref="chartRef" class="chart-container"></div>
        <p class="note">柱状图：销售数量；折线图：总销售额（元）</p>
      </div>
  
      <!-- 下载按钮 -->
      <div class="download-wrapper">
        <button class="download-btn" :disabled="!chartInstance" @click="downloadChart">
          下载图表文件
        </button>
      </div>
  
      <!-- 页面底部 -->
      <FooterInfo />
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, nextTick } from 'vue'
  import * as echarts from 'echarts'
  import FooterInfo from '../components/FooterInfo.vue'
  import axios from 'axios'
  
  const chartRef = ref(null)
  const chartInstance = ref(null)
  const apiData = ref([])
  
  const API_BASE = 'http://localhost:8080/queryCategoryOfSales'
  
  // 品牌映射表（销量前 15 必备）
  const categoryMap = {
    null: '其他',
    'electronics.smartphone': '智能手机',
    'computers.notebook': '笔记本电脑',
    'appliances.kitchen.refrigerators': '冰箱',
    'electronics.audio.headphone': '耳机',
    'electronics.video.tv': '电视',
    'appliances.environment.vacuum': '吸尘器',
    'appliances.kitchen.washer': '洗碗机',
    'appliances.kitchen.kettle': '电热水壶',
    'computers.peripherals.mouse': '鼠标',
    'furniture.kitchen.table': '餐桌',
    'appliances.kitchen.hood': '油烟机',
    'appliances.kitchen.blender': '搅拌机',
    'appliances.iron': '电熨斗',
    'appliances.kitchen.microwave': '微波炉',
    'appliances.environment.air_conditioner': '空调',
    'appliances.personal.scales': '电子秤',
    'electronics.clocks': '钟表',
    'computers.network.router': '无线路由器',
    'electronics.tablet': '平板电脑',
    'stationery.battery': '电池'
  }
  
  function mapCategoryName(cat) {
    if (cat === null || cat === undefined) return '其他'
    return categoryMap[cat] || cat.replace(/\./g, '·')
  }
  
  async function fetchData() {
    try {
      const { data: res } = await axios.get(API_BASE)
      apiData.value = res?.code === 200 ? res.data : []
      updateChart()
    } catch (err) {
      console.error('请求失败：', err)
      apiData.value = []
      updateChart()
    }
  }
  
  function updateChart() {
    if (!chartInstance.value) return
    if (!apiData.value || apiData.value.length === 0) {
      chartInstance.value.clear()
      return
    }
  
    // 取销量前 15
    const sorted = [...apiData.value].sort((a, b) => b.salesCount - a.salesCount).slice(0, 15)
  
    const categories = sorted.map(d => mapCategoryName(d.category))
    const salesCounts = sorted.map(d => d.salesCount)
    const totalSales = sorted.map(d => d.totalSales)
  
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['销售数量', '总销售额'],
        top: 0
      },
      grid: {
        left: '6%',
        right: '6%',
        bottom: '18%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: categories,
        axisLabel: {
          rotate: 30,
          interval: 0
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '销售数量',
          position: 'left'
        },
        {
          type: 'value',
          name: '总销售额（元）',
          position: 'right'
        }
      ],
      series: [
        {
          name: '销售数量',
          type: 'bar',
          data: salesCounts,
          yAxisIndex: 0,
          itemStyle: { color: '#5470C6' },
          label: {
            show: true,
            position: 'top'
          }
        },
        {
          name: '总销售额',
          type: 'line',
          data: totalSales,
          yAxisIndex: 1,
          smooth: true,
          itemStyle: { color: '#EE6666' },
          label: {
            show: true,
            position: 'top',
            formatter: v => v.value.toLocaleString()
          }
        }
      ]
    }
  
    chartInstance.value.setOption(option)
  }
  
  onMounted(async () => {
    await nextTick()
    if (!chartRef.value) return
    chartInstance.value = echarts.init(chartRef.value)
    fetchData()
  
    window.addEventListener('resize', () => {
      chartInstance.value && chartInstance.value.resize()
    })
  })
  
  function downloadChart() {
    if (!chartInstance.value) return
    const url = chartInstance.value.getDataURL({
      type: 'png',
      pixelRatio: 2,
      backgroundColor: '#fff'
    })
    const link = document.createElement('a')
    link.href = url
    link.download = 'total-sales-analysis.png'
    link.click()
  }
  </script>
  
  <style scoped>
  .brand-total-page {
    max-width: 1000px;
    margin: 40px auto;
    font-family: 'Segoe UI', sans-serif;
  }
  
  .info-card {
    background: #fff;
    padding: 25px 30px;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    margin-bottom: 25px;
  }
  .info-content {
    display: flex;
    align-items: flex-start;
    gap: 20px;
  }
  .info-image img {
    width: 240px;
    height: auto;
    border-radius: 8px;
    object-fit: cover;
    margin-top: 70px;
  }
  .info-text {
    flex: 1;
  }
  .info-text h2 {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 12px;
    color: #333;
  }
  .info-text .desc {
    font-size: 15px;
    color: #555;
    line-height: 1.8;
    text-align: justify;
  }
  
  .chart-card {
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    padding: 20px;
    margin-bottom: 20px;
  }
  .chart-container {
    width: 100%;
    height: 500px;
  }
  .note {
    text-align: center;
    font-size: 13px;
    color: #888;
    margin-top: 10px;
  }
  
  .download-wrapper {
    text-align: center;
    margin-bottom: 30px;
  }
  .download-btn {
    background: #5470C6;
    color: #fff;
    padding: 10px 22px;
    border: none;
    border-radius: 6px;
    font-size: 15px;
    cursor: pointer;
    transition: background 0.3s;
  }
  .download-btn:hover {
    background: #3b5ba4;
  }
  .download-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
  }
  </style>
  